<template>
  <view class="my-info-container">
    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
    <u-form
      labelPosition="left"
      :model="state.userInfo"
      :rules="state.rules"
      ref="formRef"
    >
      <u-form-item label="头像" prop="avatarUrl" borderBottom>
        <button
          class="avatar"
          open-type="chooseAvatar"
          @chooseavatar="onChooseAvatar"
        >
          <image
            v-if="state.userInfo?.avatarUrl"
            :src="state.userInfo?.avatarUrl"
            class="avatar-img"
          ></image>
          <image
            v-else
            src="./../../static/img/user.jpg"
            class="avatar-img"
          ></image>
        </button>
      </u-form-item>
      <u-form-item label="工号" prop="workNumber" borderBottom>
        <u-input v-model="state.userInfo.workNumber" border="none"></u-input>
      </u-form-item>
      <u-form-item label="姓名" prop="username" borderBottom>
        <u-input v-model="state.userInfo.username" border="none"></u-input>
      </u-form-item>
      <u-form-item
        label="电话号码"
        labelWidth="80"
        prop="phoneNumber"
        borderBottom
      >
        <u-input v-model="state.userInfo.phoneNumber" border="none"></u-input>
      </u-form-item>
      <u-form-item
        label="车牌号"
        labelWidth="60"
        prop="licensePlateNumber"
        borderBottom
      >
        <u-input
          v-model="state.userInfo.licensePlateNumber"
          border="none"
        ></u-input>
      </u-form-item>
      <u-form-item
        v-if="false"
        label="性别"
        prop="sex"
        borderBottom
        @click="state.showSex = true"
      >
        <u-input
          v-model="state.userInfo.sex"
          disabled
          disabledColor="#ffffff"
          placeholder="请选择性别"
          border="none"
        ></u-input>
        <template #right>
          <u-icon name="arrow-right"></u-icon>
        </template>
      </u-form-item>
    </u-form>
    <u-action-sheet
      v-if="false"
      :show="state.showSex"
      :actions="state.actions"
      title="请选择性别"
      description="如果选择保密会报错"
      @close="state.showSex = false"
      @select="sexSelect"
    >
    </u-action-sheet>
    <!-- handle-bar -->
    <u-button
      type="primary"
      text="提交"
      customStyle="margin-top: 50px"
      @click="submit"
    ></u-button>
    <u-button
      v-if="false"
      type="error"
      text="重置"
      customStyle="margin-top: 10px"
      @click="reset"
    ></u-button>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { updateUserInfo, getUserInfo } from "@/utils/api/user.js";

import useUserStore from "@/store/user.js";
const userStore = useUserStore();
// 使用 reactive 创建响应式状态
const state = reactive({
  showSex: false,
  userInfo: {
    openId: userStore.openid,
    username: "",
    // sex: "",
    phoneNumber: "",
    licensePlateNumber: "",
    workNumber: "",
    avatarUrl: "",
  },
  //   actions: [{ name: "男" }, { name: "女" }, { name: "保密" }],
  rules: {
    username: {
      type: "string",
      required: true,
      message: "请填写姓名",
      trigger: ["blur", "change"],
    },
  },
  radio: "",
  switchVal: false,
});

// 使用 ref 创建响应式引用
const formRef = ref(null);

// 定义方法
function sexSelect(e) {
  state.userInfo.sex = e.name;
  console.log("state:", state);

  if (formRef.value) {
    formRef.value.validateField("userInfo.sex");
  }
}
const sendUserInfo = () => {
  // 调用接口更新用户信息
  updateUserInfo(state.userInfo)
    .then((res) => {
      uni.$u.toast("更新成功");
      uni.showToast({
        title: "更新成功",
        duration: 1000,
        success() {
          setTimeout(() => {
            uni.switchTab({ url: "/pages/my/my" });
          }, 1000);
        },
      });
    })
    .catch((err) => {
      uni.$u.toast("更新失败");
    });
};
const onChooseAvatar = async (e) => {
  console.log("e:", e);

  const tempFilePath = e.detail.avatarUrl; //上传的图片地址
  uni.setStorageSync("avatar", tempFilePath);
  const maxSizeInBytes = 1024 * 1024; // 限制大小为1MB
  uni.getFileSystemManager().getFileInfo({
    filePath: tempFilePath,
    success: (res) => {
      console.log("res:", res);

      const fileSize = res.size;
      if (fileSize > maxSizeInBytes) {
        //如果上传的图片大小超过1MB，进行提示
        uni.$showMsg("请上传小于1MB的图片");
        return;
      }
      // console.log("tempFilePath:", tempFilePath);

      // //图片大小符合，替换图片
      // state.userInfo.avatarUrl = tempFilePath;
    },
  });
  // wx.getFileSystemManager().access({
  //   path: tempFilePath,
  //   success() {
  //     // 文件存在，继续读取
  //     wx.getFileSystemManager().readFile({
  //       filePath: tempFilePath,
  //       encoding: "base64",
  //       success(result) {
  //         const base64Data = result.data;
  //         state.userInfo.avatarUrl = base64Data;
  //       },
  //       fail(error) {
  //         console.error("读取文件失败:", error);
  //       },
  //     });
  //   },
  //   fail() {
  //     console.error("文件不存在:", tempFilePath);
  //   },
  // });
  wx.getFileSystemManager().readFile({
    filePath: tempFilePath,
    encoding: "base64",
    success(result) {
      console.log("result:", result);
      state.userInfo.avatarUrl = "data:image/png;base64," + result.data;
      // const base64Data = result.data;
      // console.log("Base64 编码:", base64Data);
      // // 这里可以将 base64Data 保存到本地或上传到服务器
    },
    fail(error) {
      console.error("读取文件失败:", error);
    },
  });
};
const submit = () => {
  // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
  formRef.value
    .validate()
    .then((res) => {
      if (res) {
        sendUserInfo();
      }
    })
    .catch((errors) => {
      console.log(errors);
      uni.$u.toast("校验失败");
    });
};

const reset = () => {
  const validateList = [];
  formRef.value.resetFields();
  formRef.value.clearValidate(validateList);
  //   setTimeout(() => {
  //     formRef.value.clearValidate(validateList);
  //     // 或者使用 this.$refs.form1.clearValidate()
  //   }, 10);
};
// const hideKeyboard = () => {
//   uni.hideKeyboard();
// };
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo({ openId: userStore.openid });
    if (res) {
      Object.assign(state.userInfo, res);
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
};
onMounted(() => {
  fetchUserInfo();
});
</script>

<style lang="scss" scoped>
.my-info-container {
  padding: 20px;
  background-color: #fff;
  .avatar {
    box-sizing: border-box;
    width: 46px;
    height: 46px;
    background-color: rgba(217, 217, 217, 1);
    border-radius: 50%;
    border: 2rpx solid rgba(217, 217, 217, 1);
    box-shadow: 1rpx 1rpx 8rpx rgb(74, 71, 71);
    padding: 0;
    margin: 0;

    .avatar-img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
